import numpy as np

#--------------------------------------------------------------------------
#MAIN
if __name__ == "__main__":
    print '============='
    filePath = 'C:/_DATA/migration89_08/COUNTY Migration/CO9091/Co9091_ascii/Co9091out_ascii/'
    totalOutput = np.array([])
    row = 0
    state = ['al', 'ak', 'az', 'ar', 'ca', 'co', 'ct', 'de', 'fl', 'ga', 'hi', 'id', 'il', 'in', 'ia', 'ks', 'ky', 'la', 'me', 'md', 'ma', 'mi', 'mn', 'ms', 'mo', 'mt', 'ne', 'nv', 'nh', 'nj', 'nm', 'ny', 'nc', 'nd', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'vt', 'va', 'wa', 'wv', 'wi', 'wy']
    for st in state:
        print st
        inputfile = filePath + 'C9091'+ st +'o.txt'
        f = open(inputfile,'r')
        line = f.readline()
        output = []

        #for i in range(0,10):
        while line:
            row += 1
            if line[0] <> ' ':
                # new county starts
                o_state = line[:2]
                o_county = line[3:6]
                other_in = 0.0
                other_out = 0.0
                output.append([o_state, o_county, '96', '000', float(line[38:46]), float(line[53:63])])
            elif line[2] <> ' ':
                # county-to-county flow
                output.append([o_state, o_county, line[2:4], line[5:8], float(line[38:46]), float(line[53:63])])
            elif line[3] <> ' ':
                # other flow
                other_in += float(line[38:46])
                other_out += float(line[53:63])
            else:
                # non-migrants
                output.append([o_state, o_county, '59', '000', other_in, other_out])
                output.append([o_state, o_county, o_state, o_county, float(line[38:46]), float(line[53:63])])
            line = f.readline()
        f.close()
        totalOutput = np.append(totalOutput, output)
        #print output
        
        outputPath = inputfile[:-4] + '.csv'
        np.savetxt(outputPath, output, delimiter=',', fmt = '%s')
    outputPath = inputfile[:-7] + '.csv'
    #totalOutput = np.array(totalOutput)
    totalOutput.shape = (-1, 6)
    np.savetxt(outputPath, totalOutput, delimiter=',', fmt = '%s')
        

